<template>
  <div class="Login">
    <shop-header>登录</shop-header>
    <shop-logo></shop-logo>
    <van-field
      v-model="username"
      label="用户名"
      placeholder="请输入用户名"
      :error-message="usernameErrMes"
      clearable
      @input="checkUsername"
    />
    <van-field
      v-model="password"
      type="password"
      placeholder="请输入密码"
      label="密码"
      :error-message="passwordErrMes"
      clearable
      @input="checkpassword"
    />
    <shop-button @click.native="login">登录</shop-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: "",
      password: "",
      usernameErrMes: "",
      passwordErrMes: "",
    };
  },
  created() {
    console.log(this.$route);
    const { username, password } = this.$route.params;
    this.username = username;
    this.password = password;
  },
  methods: {
    checkUsername() {
      if (this.username == "") {
        this.usernameErrMes = "";
      } else {
        const reg = /^1\d{3,7}$/;
        if (reg.test(this.username)) {
          this.usernameErrMes = "";
        } else {
          this.usernameErrMes = "用户名格式不正确";
        }
      }
    },
    checkpassword() {
      if (this.password == "") {
        this.passwordErrMes = "";
      } else {
        const reg = /^\d{3,12}$/;
        if (reg.test(this.password)) {
          this.passwordErrMes = "";
        } else {
          this.passwordErrMes = "密码格式不正确";
        }
      }
    },
    async login() {
      if (
        this.usernameErrMes == "" &&
        this.passwordErrMes == "" &&
        this.password != "" &&
        this.username != ""
      ) {
        const res = await this.$axios.post("/login", {
          username: this.username,
          password: this.password,
        });
        console.log(res);
        const { message, statusCode, data } = res.data;
        if (statusCode == 200) {
          this.$toast.success(message);
          localStorage.setItem("token", data.token);
          localStorage.setItem("id", data.user.id);
          this.$router.push({
            path: "/user",
          });
        } else {
          this.$toast.fail(message);
        }
      } else {
        this.$toast.fail("请输入争取的信息");
      }
    },
  },
};
</script>

<style></style>
